package cn.tedu.smartos.family_user.controller;

import cn.tedu.smartos.base.response.JsonResult;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.family_user.pojo.vo.BoundElderlyVO;
import cn.tedu.smartos.family_user.pojo.vo.ElderlyHealthInfoVO;
import cn.tedu.smartos.family_user.service.ElderlyHealthService;
import org.springframework.beans.factory.annotation.Value;
import org.apache.commons.io.FilenameUtils;
import cn.tedu.smartos.family_user.pojo.dto.FamilyUserUpdateParam;
import cn.tedu.smartos.family_user.pojo.dto.PasswordUpdateParam;
import cn.tedu.smartos.family_user.pojo.vo.FamilyUserVO;
import cn.tedu.smartos.family_user.service.FamilyUserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "家属模块")
@Slf4j
@RestController
@RequestMapping("/api/v1/family_user/")
public class FamilyUserController {
    @Autowired
    private FamilyUserService familyUserService;
    @Autowired
    private ElderlyHealthService elderlyHealthService;

    //新增：注入配置
    @Value("${smartos.upload.avatar-path}")
    private String avatarPath;

    @Value("${smartos.upload.avatar-url-prefix}")
    private String avatarUrlPrefix;

    // 个人信息查询
    @ApiOperation("家属个人信息查看")
    @ApiOperationSupport(order = 10)
    @GetMapping("info/{userId}")
    public JsonResult getFamilyUserInfo(@PathVariable Long userId) {
        FamilyUserVO familyInfo = familyUserService.getFamilyUserInfo(userId);
        // 创建统一响应结构
        Map<String, Object> data = new HashMap<>();
        data.put("code", 2000); // 匹配前端期望的状态码
        data.put("message", "操作成功");
        data.put("data", familyInfo); // 将数据放在data字段
        return JsonResult.ok(data); // 返回统一结构
    }

    @ApiOperation("家属个人信息修改")
    @ApiOperationSupport(order = 20)
    @PostMapping("info")
    public JsonResult update(@Valid @RequestBody FamilyUserUpdateParam updateParam) {
        log.info("接收更新参数: {}", updateParam);
        familyUserService.update(updateParam);
        return JsonResult.ok("信息更新成功！");
    }


    @ApiOperation("修改密码")
    @ApiOperationSupport(order = 30)
    @PostMapping("password")
    public JsonResult updatePassword(@RequestBody PasswordUpdateParam passwordParam) {
        log.debug("修改密码: {}", passwordParam);
        familyUserService.updatePassword(passwordParam);
        return JsonResult.ok("密码更新成功");
    }

    @ApiOperation("修改头像")
    @ApiOperationSupport(order = 40)
    @PostMapping("avatar")
    public JsonResult updateAvatar(@RequestParam Long userId,
                                   @RequestParam("avatarFile") MultipartFile avatarFile) throws IOException {
        if (avatarFile.isEmpty()) {
            return JsonResult.fail("文件为空");
        }

        String suffix = FilenameUtils.getExtension(avatarFile.getOriginalFilename()).toLowerCase();
        if (!Arrays.asList("jpg", "jpeg", "png").contains(suffix)) {
            return JsonResult.fail("仅支持 jpg/png");
        }

        // 确保目录存在
        Path uploadDir = Paths.get(avatarPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        // 文件名：userId.jpg
        String fileName = userId + "." + suffix;
        Path targetPath = uploadDir.resolve(fileName);

        // 保存文件
        Files.copy(avatarFile.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

        // 返回可访问的URL
//        String avatarUrl = avatarUrlPrefix + "/avatars/" + fileName;


        String avatarUrl = avatarUrlPrefix + "/avatars/" + fileName;
        familyUserService.updateAvatar(userId, avatarUrl);
        return JsonResult.ok(avatarUrl);
    }
    @ApiOperation("获取绑定的老人列表")
    @GetMapping("elderly/list")
    public JsonResult listBoundElderly(@RequestParam(required = true) Long userId) {
        log.debug("开始处理【获取绑定的老人列表】的请求，userId: {}", userId);
        // 确保调用的是正确的服务方法
        List<BoundElderlyVO> list = elderlyHealthService.listBoundElderly(userId);
        return JsonResult.ok(list);
    }
}